/**
 * 从事件中抽graphic
 * @param {*} event
 * @returns
 */
export function graphicFromEvent(event) {
  if (event.graphics && event.graphics.length) {
    return event.graphics[0];
  }
  return event.graphic;
}

/**
 * 检测当前屏幕上的点是否超出规划区域，超出只能贴边规划区域的边
 * @param {*} point
 * @param {*} maskPolygon
 * @returns
 */
export function snapPoint(point, maskPolygon) {
  if (!maskPolygon) {
    return point;
  }
  // const maskPolygon = this.scene.maskPolygon;
  return geometryEngine.nearestCoordinate(maskPolygon, point).coordinate;
}

/**
 * 更新graphic的geometry
 * @param {*} geometry
 * @param {*} graphic
 * @param {*} targetLayer
 * @returns
 */
export function updateGraphicFromGeometry(geometry, graphic, targetLayer) {
  if (geometry) {
    graphic.geometry = geometry; //更新 geometry
    graphic.visible = true;

    if (!graphic.layer) {
      if (!targetLayer) {
        console.error('请传入graphic的目标图层');
        return;
      }
      //传入的graphic不带图层，添加graphic到当前激活的图层
      targetLayer.add(graphic);
    }
  } else {
    // 防错处理
    graphic.visible = false;
  }
}

/**
 * 从graphic中抽出geometry
 * @param {*} sketchGraphic
 * @returns
 */
export function geometryFromSketch(sketchGraphic) {
  return sketchGraphic.geometry.clone();
}

export function createGraphic(ctx) {
  let sketchGraphic;
  switch (ctx.geometryType) {
    case 'polyline':
      sketchGraphic = ctx.graphic.clone();
      sketchGraphic.symbol = ctx.sketchViewModel.polygonSymbol;
      console.log(sketchGraphic, ctx, 'createGraphic');
      return sketchGraphic;
    case 'polygon':
      sketchGraphic = ctx.graphic.clone();
      sketchGraphic.symbol = ctx.sketchViewModel.polygonSymbol;
      return sketchGraphic;
    case 'point':
    default:
      return ctx.graphic;
  }
}

export function splitPolyline(polyline, graphic) {
  const graphics = [];
  if (1 < polyline.paths.length) {
    polyline.paths.forEach((path) => {
      const clonedGraphic = graphic.clone();
      clonedGraphic.geometry.paths = [path];
      graphics.push(clonedGraphic);
    });
  } else {
    graphics.push(graphic);
  }
  return graphics;
}